<template>
  <div class="memory-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">
          <el-icon><DataAnalysis /></el-icon>
          内存分析
        </h2>
        <p class="page-description">
          {{ appStore.currentProductName }} - 共 {{ memoryStore.total }} 个进程
        </p>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          :icon="Refresh"
          @click="refreshData"
          :loading="memoryStore.loading"
        >
          刷新数据
        </el-button>
        <el-button
          :icon="Download"
          @click="exportData"
          :disabled="memoryStore.loading"
        >
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 内存统计卡片 -->
    <el-row :gutter="24" style="margin-bottom: 24px;">
      <el-col :span="6">
        <el-card class="stats-card" shadow="never">
          <div class="stat-item">
            <div class="stat-label">总RSS</div>
            <div class="stat-value">{{ formatBytes(memoryStore.memoryStatsSummary.rssTotal) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="never">
          <div class="stat-item">
            <div class="stat-label">总PSS</div>
            <div class="stat-value">{{ formatBytes(memoryStore.memoryStatsSummary.pssTotal) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="never">
          <div class="stat-item">
            <div class="stat-label">共享内存</div>
            <div class="stat-value">{{ formatBytes(memoryStore.memoryStatsSummary.sharedCleanTotal + memoryStore.memoryStatsSummary.sharedDirtyTotal) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card" shadow="never">
          <div class="stat-item">
            <div class="stat-label">私有内存</div>
            <div class="stat-value">{{ formatBytes(memoryStore.memoryStatsSummary.privateCleanTotal + memoryStore.memoryStatsSummary.privateDirtyTotal) }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" @submit.prevent="applyFilters" class="search-form">
        <el-form-item label="搜索进程">
          <el-input
            v-model="localFilters.search"
            placeholder="进程名、PID..."
            :prefix-icon="Search"
            clearable
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="进程类别">
          <el-select
            v-model="localFilters.category"
            placeholder="全部类别"
            clearable
            style="width: 180px"
          >
            <el-option label="系统进程" value="system" />
            <el-option label="应用进程" value="app" />
            <el-option label="服务进程" value="service" />
            <el-option label="内核进程" value="kernel" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select
            v-model="localFilters.sortBy"
            style="width: 150px"
          >
            <el-option label="RSS" value="Rss" />
            <el-option label="PSS" value="Pss" />
            <el-option label="共享内存" value="Shared_Clean" />
            <el-option label="私有内存" value="Private_Dirty" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Filter" @click="applyFilters">筛选</el-button>
          <el-button :icon="RefreshLeft" @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 错误提示 -->
    <el-alert
      v-if="memoryStore.error"
      :title="memoryStore.error"
      type="error"
      show-icon
      :closable="false"
      class="error-alert"
    />

    <!-- 进程内存表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="memoryStore.loading"
        :data="memoryStore.paginatedProcesses"
        style="width: 100%"
        row-key="pid"
        @sort-change="onSortChange"
        stripe
      >
        <el-table-column prop="pid" label="PID" width="80" sortable="custom" />
        <el-table-column prop="process" label="进程名" min-width="200" sortable="custom">
          <template #default="{ row }">
            <el-link
              type="primary"
              :underline="false"
              @click="viewProcessDetail(row.pid)"
            >
              {{ row.process || row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="类别" width="100" sortable="custom">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)" size="small">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="threads" label="线程" width="80" align="center" sortable="custom" />
        <el-table-column prop="objects" label="对象" width="80" align="center" sortable="custom" />
        <el-table-column prop="vmas" label="VMA" width="80" align="center" sortable="custom" />
        <el-table-column prop="Rss" label="RSS" width="100" align="right" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(row.Rss) }}
          </template>
        </el-table-column>
        <el-table-column prop="Pss" label="PSS" width="100" align="right" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(row.Pss) }}
          </template>
        </el-table-column>
        <el-table-column prop="Shared_Clean" label="共享干净页" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(row.Shared_Clean) }}
          </template>
        </el-table-column>
        <el-table-column prop="Shared_Dirty" label="共享脏页" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(row.Shared_Dirty) }}
          </template>
        </el-table-column>
        <el-table-column prop="Private_Dirty" label="私有脏页" width="120" align="right" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(row.Private_Dirty) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="viewProcessDetail(row.pid)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="memoryStore.currentPage"
          :page-size="memoryStore.pageSize"
          :total="memoryStore.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 进程详情对话框 -->
    <el-dialog
      v-model="processDetailVisible"
      :title="`进程详情 - ${currentProcess?.process || currentProcess?.name} (PID: ${currentProcess?.pid})`"
      width="80%"
      top="5vh"
    >
      <div v-if="currentProcess">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="PID">{{ currentProcess.pid }}</el-descriptions-item>
              <el-descriptions-item label="进程名">{{ currentProcess.process || currentProcess.name }}</el-descriptions-item>
              <el-descriptions-item label="类别">{{ getCategoryLabel(currentProcess.category) }}</el-descriptions-item>
              <el-descriptions-item label="线程数">{{ currentProcess.threads || 0 }}</el-descriptions-item>
              <el-descriptions-item label="对象数">{{ currentProcess.objects || 0 }}</el-descriptions-item>
              <el-descriptions-item label="VMA数">{{ currentProcess.vmas || 0 }}</el-descriptions-item>
              <el-descriptions-item label="RSS">{{ formatBytes(currentProcess.Rss) }}</el-descriptions-item>
              <el-descriptions-item label="PSS">{{ formatBytes(currentProcess.Pss) }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="内存分布" name="memory">
            <div class="memory-chart-container">
              <div id="memoryChart" style="width: 100%; height: 400px;"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  DataAnalysis,
  Refresh,
  Download,
  Search,
  Filter,
  RefreshLeft
} from '@element-plus/icons-vue'
import { useMemoryStore } from '@/stores/memory'
import { useAppStore } from '@/stores/app'
import * as echarts from 'echarts'

const memoryStore = useMemoryStore()
const appStore = useAppStore()
const router = useRouter()

// 本地筛选条件，避免直接修改store
const localFilters = ref({
  search: '',
  category: '',
  sortBy: 'Rss',
  sortOrder: 'desc'
})

// 进程详情对话框
const processDetailVisible = ref(false)
const currentProcess = ref(null)
const activeTab = ref('basic')
let memoryChart = null

// 方法
const refreshData = async () => {
  if (!appStore.currentProduct || !appStore.currentVersion) {
    ElMessage.warning('请先选择一个产品版本')
    return
  }
  try {
    await memoryStore.fetchProcesses(appStore.currentProduct, appStore.currentVersion)
    ElMessage.success('内存数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  }
}

const exportData = () => {
  ElMessageBox.confirm('确定要导出当前筛选结果的内存数据吗？', '确认导出', {
    type: 'info',
    confirmButtonText: '导出CSV',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      const blob = memoryStore.exportProcesses('csv')
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')
      link.href = url
      link.download = `memory_${appStore.currentProductName}_${timestamp}.csv`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      ElMessage.success('内存数据导出成功')
    } catch (error) {
      ElMessage.error('导出失败，请重试')
    }
  }).catch(() => {})
}

const applyFilters = () => {
  memoryStore.setFilters(localFilters.value)
}

const resetFilters = () => {
  localFilters.value = {
    search: '',
    category: '',
    sortBy: 'Rss',
    sortOrder: 'desc'
  }
  memoryStore.clearFilters()
}

const onSortChange = ({ prop, order }) => {
  const sortOrder = order === 'ascending' ? 'asc' : 'desc'
  memoryStore.setFilters({ sortBy: prop, sortOrder })
  localFilters.value.sortBy = prop
  localFilters.value.sortOrder = sortOrder
}

const handleSizeChange = (size) => {
  memoryStore.setPageSize(size)
}

const handleCurrentChange = (page) => {
  memoryStore.setCurrentPage(page)
}

const viewProcessDetail = async (processId) => {
  try {
    const process = memoryStore.processes.find(p => p.pid == processId)
    if (process) {
      currentProcess.value = process
      processDetailVisible.value = true

      // 等待DOM更新后绘制图表
      await nextTick()
      drawMemoryChart(process)
    }
  } catch (error) {
    ElMessage.error('获取进程详情失败')
  }
}

const drawMemoryChart = (process) => {
  if (memoryChart) {
    memoryChart.dispose()
  }

  const chartDom = document.getElementById('memoryChart')
  if (!chartDom) return

  memoryChart = echarts.init(chartDom)

  const data = [
    { name: '共享干净页', value: parseFloat(process.Shared_Clean) || 0 },
    { name: '共享脏页', value: parseFloat(process.Shared_Dirty) || 0 },
    { name: '私有干净页', value: parseFloat(process.Private_Clean) || 0 },
    { name: '私有脏页', value: parseFloat(process.Private_Dirty) || 0 }
  ].filter(item => item.value > 0)

  const option = {
    title: {
      text: '内存分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '内存分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          ...item,
          value: Math.round(item.value / 1024) // Convert to KB for better display
        }))
      }
    ]
  }

  memoryChart.setOption(option)
}

const getCategoryTagType = (category) => {
  const typeMap = {
    'system': 'danger',
    'app': 'success',
    'service': 'primary',
    'kernel': 'warning'
  }
  return typeMap[category] || 'info'
}

const getCategoryLabel = (category) => {
  const labelMap = {
    'system': '系统',
    'app': '应用',
    'service': '服务',
    'kernel': '内核'
  }
  return labelMap[category] || category
}

const formatBytes = (bytes) => {
  return memoryStore.formatBytes(bytes)
}

// 监听产品变化
watch(() => [appStore.currentProduct, appStore.currentVersion], ([newProduct, newVersion]) => {
  if (newProduct && newVersion) {
    memoryStore.fetchProcesses(newProduct, newVersion)
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  if (!appStore.currentProduct && appStore.products.length > 0) {
    // 获取第一个产品的信息
    const firstProduct = appStore.products[0]
    if (typeof firstProduct === 'string') {
      appStore.setCurrentProduct(firstProduct, '')
    } else {
      appStore.setCurrentProduct(firstProduct.name || firstProduct.id, firstProduct.version || '')
    }
  }
  if (appStore.currentProduct && appStore.currentVersion) {
    memoryStore.fetchProcesses(appStore.currentProduct, appStore.currentVersion)
  }
})
</script>

<style scoped lang="scss">
.memory-page {
  // 深色模式页面背景
  background: var(--el-bg-color);
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    transition: all 0.3s ease;

    .header-content {
      .page-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        transition: color 0.3s ease;

        .el-icon {
          color: var(--el-color-primary);
        }
      }
      .page-description {
        margin: 0;
        color: var(--el-text-color-regular);
        transition: color 0.3s ease;
      }
    }

    .header-actions {
      .el-button {
        transition: all 0.3s ease;
      }
    }
  }

  .stats-card {
    background: var(--el-bg-color);
    border-color: var(--el-border-color);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: var(--el-box-shadow-light);
      transform: translateY(-1px);
    }

    .stat-item {
      text-align: center;
      padding: 20px 16px;
      transition: all 0.3s ease;

      &:hover {
        background: var(--el-fill-color-light);
        border-radius: 8px;
      }

      .stat-label {
        font-size: 12px;
        color: var(--el-text-color-regular);
        margin-bottom: 8px;
        transition: color 0.3s ease;
      }

      .stat-value {
        font-size: 20px;
        font-weight: 600;
        color: var(--el-color-primary);
        transition: color 0.3s ease;
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
    background: var(--el-bg-color);
    border-color: var(--el-border-color);
    transition: all 0.3s ease;

    .search-form {
      .el-form-item {
        margin-bottom: 0;

        .el-form-item__label {
          color: var(--el-text-color-regular);
        }
      }
    }

    // 深色模式下表单控件样式
    :deep(.el-input) {
      --el-input-bg-color: var(--el-fill-color-blank);
      --el-input-border-color: var(--el-border-color);
      --el-input-text-color: var(--el-text-color-primary);
      --el-input-placeholder-color: var(--el-text-color-placeholder);
    }

    :deep(.el-select) {
      --el-select-input-color: var(--el-text-color-primary);
      --el-select-border-color: var(--el-border-color);
    }

    :deep(.el-button) {
      transition: all 0.3s ease;
    }
  }

  .error-alert {
    margin-bottom: 20px;
    border-left: 4px solid var(--el-color-danger);
    background: var(--el-color-danger-light-9);
    transition: all 0.3s ease;

    @at-root .dark .memory-page .error-alert {
      background: rgba(245, 108, 108, 0.1);
      border-color: var(--el-color-danger);
    }
  }

  .table-card {
    background: var(--el-bg-color);
    border-color: var(--el-border-color);
    transition: all 0.3s ease;

    .el-table {
      --el-table-bg-color: var(--el-bg-color);
      --el-table-tr-bg-color: var(--el-bg-color);
      --el-table-header-bg-color: var(--el-fill-color-light);
      --el-table-border-color: var(--el-border-color-lighter);
      --el-table-text-color: var(--el-text-color-primary);
      --el-table-header-text-color: var(--el-text-color-primary);
      --el-table-row-hover-bg-color: var(--el-fill-color-light);

      // 表格行深色模式优化
      th.el-table__cell {
        background: var(--el-fill-color-light);
        border-bottom-color: var(--el-border-color-lighter);
        color: var(--el-text-color-primary);
      }

      td.el-table__cell {
        border-bottom-color: var(--el-border-color-lighter);
        color: var(--el-text-color-primary);
      }

      .el-table__body tr:hover > td {
        background: var(--el-fill-color-light);
      }
    }

    .el-link {
      font-weight: 500;
      color: var(--el-color-primary);
      transition: color 0.3s ease;

      &:hover {
        color: var(--el-color-primary-light-3);
      }
    }

    // 标签深色模式
    :deep(.el-tag) {
      background: var(--el-fill-color-light);
      color: var(--el-text-color-primary);
      border-color: var(--el-border-color);

      &.el-tag--success {
        background: var(--el-color-success-light-9);
        color: var(--el-color-success);
        border-color: var(--el-color-success-light-7);
      }

      &.el-tag--danger {
        background: var(--el-color-danger-light-9);
        color: var(--el-color-danger);
        border-color: var(--el-color-danger-light-7);
      }

      &.el-tag--warning {
        background: var(--el-color-warning-light-9);
        color: var(--el-color-warning);
        border-color: var(--el-color-warning-light-7);
      }

      &.el-tag--primary {
        background: var(--el-color-primary-light-9);
        color: var(--el-color-primary);
        border-color: var(--el-color-primary-light-7);
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
      padding-top: 16px;
      border-top: 1px solid var(--el-border-color-lighter);

      :deep(.el-pagination) {
        --el-pagination-button-bg-color: var(--el-fill-color-blank);
        --el-pagination-hover-color: var(--el-color-primary);
        --el-pagination-text-color: var(--el-text-color-regular);
        --el-pagination-disabled-color: var(--el-text-color-placeholder);
      }
    }
  }

  .memory-chart-container {
    padding: 20px;
    background: var(--el-bg-color);
    border-radius: 8px;
    transition: all 0.3s ease;

    // 图表容器深色模式
    #memoryChart {
      background: var(--el-bg-color);
    }
  }
}

// 深色模式卡片样式优化
:deep(.el-card) {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
  transition: all 0.3s ease;

  .el-card__header {
    background: var(--el-bg-color);
    border-bottom-color: var(--el-border-color-lighter);
    color: var(--el-text-color-primary);
  }

  .el-card__body {
    background: var(--el-bg-color);
    color: var(--el-text-color-primary);
  }
}

// 深色模式对话框样式优化
:deep(.el-dialog) {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);

  .el-dialog__header {
    border-bottom-color: var(--el-border-color-lighter);
    background: var(--el-bg-color);

    .el-dialog__title {
      color: var(--el-text-color-primary);
    }
  }

  .el-dialog__body {
    background: var(--el-bg-color);
    color: var(--el-text-color-primary);
  }

  .el-dialog__footer {
    border-top-color: var(--el-border-color-lighter);
    background: var(--el-bg-color);
  }
}

// 深色模式Tabs样式优化
:deep(.el-tabs) {
  .el-tabs__header {
    .el-tabs__nav-wrap {
      &::after {
        background: var(--el-border-color-lighter);
      }
    }

    .el-tabs__item {
      color: var(--el-text-color-regular);
      transition: color 0.3s ease;

      &:hover {
        color: var(--el-color-primary);
      }

      &.is-active {
        color: var(--el-color-primary);
      }
    }
  }

  .el-tabs__content {
    color: var(--el-text-color-primary);
  }
}

// 进度条深色模式
:deep(.el-progress-bar) {
  .el-progress-bar__outer {
    background: var(--el-fill-color-blank);
  }
}
</style>